package com.qingke.note.command_impl;

import java.util.Collections;
import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.qingke.note.Console;
import com.qingke.note.IDao.NoteMapper;
import com.qingke.note.command.Command;
import com.qingke.note.comparators.OrderByLabel;
import com.qingke.note.comparators.OrderByTime;
import com.qingke.note.pojo.Note;
import com.qingke.note.pojo.User;

public class ListCommand extends Command {

	public ListCommand(User user) {
		super(user);
		// TODO Auto-generated constructor stub
	}

	public int printed = 0;

	@Override
	public void execute() {
		if (currentUser == null) {
			Console.println("您还未登录，不能执行此操作");
			return;
		}

		List<Note> notes = currentUser.getNotes();
		Console.println("请选择要查询的排序方式");
		Console.println("【1】按创建顺序排序");
		Console.println("【2】按提醒时间排序");
		Console.println("【3】标题模糊查找");
		Console.println("【4】内容模糊查找");
		Console.println("【5】按标签排序");
		int choice = Console.askInputInt("请选择序号");
		while (true) {
			switch (choice) {
			case 1:
				print(notes);
				break;
			case 2:
				printByTime(notes);
				break;
			case 3:
				printByTitle();
				break;
			case 4:
				printByContent();
				break;
			case 5:
				printByLabel(notes);
				break;
			default:
				Console.println("序号不正确");
				choice = Console.askInputInt("请重新输入序号");
				continue;
			}
			break;
		}

	}

	private void printByLabel(List<Note> notes) {
		Collections.sort(notes, new OrderByLabel());
		print(notes);

	}

	private void printByContent() {
		String keyword = Console.askInput("要搜索的内容关键字");
		SqlSession session = getSession();
		NoteMapper noteMapper = session.getMapper(NoteMapper.class);
		List<Note> notes = noteMapper.selectByContent("%" + keyword + "%");
		print(notes);
		session.close();
	}

	private void printByTitle() {
		String keyword = Console.askInput("要搜索的标题关键字");
		SqlSession session = getSession();
		NoteMapper noteMapper = session.getMapper(NoteMapper.class);
		List<Note> notes = noteMapper.selectByTitle("%" + keyword + "%");
		print(notes);
		session.close();
	}

	private void printByTime(List<Note> notes) {
		// TODO Auto-generated method stub
		Collections.sort(notes, new OrderByTime());
		print(notes);
	}

	private void print(List<Note> notes) {
		
		for (Note note : notes) {
			if ("N".equals(note.getEffective())) {
				continue;
			}
			printed++;
			Console.print("【" + printed + "】");
			Console.println(note);
		}
		if (printed == 0) {
			Console.println("您还没有添加备忘");
		}
	}

}
